package com.example.servicemodule

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    private lateinit var et_aidl_id :EditText
    private lateinit var studentService:IMyAidlInterface
    private  val TAG = "MainActivity"
    private  var connection:ServiceConnection?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        this.et_aidl_id=findViewById(R.id.et_aidl_id)
    }



    fun bindRemoteService(view: View) {
        val intent = Intent("android.intent.action.RESPOND_VIA_MESSAGE")
        intent.setPackage("com.example.servicemodule")
        this.connection= object:ServiceConnection{
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//            TODO("Not yet implemented")
                studentService=IMyAidlInterface.Stub.asInterface(service)
                Log.e("", "onServiceConnected: " )
            }

            override fun onServiceDisconnected(name: ComponentName?) {
//            TODO("Not yet implemented")
            }
        }
        bindService(intent, this.connection as ServiceConnection, BIND_AUTO_CREATE)
        Toast.makeText(this,"绑定Service",Toast.LENGTH_SHORT).show()
    }
    fun invokeRemote(view: View) {

        val student=this.studentService.getStudentById(et_aidl_id.text.toString().toInt())
        Toast.makeText(this,student.toString(),Toast.LENGTH_SHORT).show()
    }
    fun unbindRemoteService(view: View) {
        if(connection==null){

        }else{
            unbindService(connection!!)
            connection=null
        }
    }

}